package com.example.lll.lll_20_weather;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private TextView tvCity,tvTemperature,tvHumidity,tvPm25;
    private RecyclerView rvForecast;
    private TextView tvTime;
    private ImageView ivWeatherIcon,ivBackground;
    private Spinner citySpinner;
    private ImageButton btnShare;
    private EditText etSearch;
    private Handler timeHandler;
    private Runnable timeRunnable;
    private List<WeatherResponse.CityWeather> cityWeatherList;
    private ArrayAdapter<String> cityAdapter;

    public String url = "http://192.168.0.102:8080/weather/weather.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ivBackground = findViewById(R.id.ivBackground);
        setupViews();
        setupTimeUpdater();
        setupShareButton();
        setupSearchFunction();
        loadWeatherData();
    }

    private void setupViews(){
        tvCity = findViewById(R.id.tvCity);
        tvHumidity = findViewById(R.id.tvHumidity);
        tvPm25 = findViewById(R.id.tvPm25);
        tvTime = findViewById(R.id.tvTime);
        tvTemperature = findViewById(R.id.tvTemperature);
        ivWeatherIcon = findViewById(R.id.ivWeatherIcon);
        citySpinner = findViewById(R.id.citySpinner);
        btnShare = findViewById(R.id.btnShare);
        etSearch = findViewById(R.id.etSearch);

        // 设置默认文本
        tvCity.setText("城市：加载中...");
        tvHumidity.setText("湿度：--");
        tvPm25.setText("PM2.5：--");
        tvTime.setText("更新时间：--");
        tvTemperature.setText("--℃");

        rvForecast = findViewById(R.id.rvForecast);
        rvForecast.setLayoutManager(new LinearLayoutManager(this));
    }

    private void setupSearchFunction(){
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    performSearch();
                    return true;
                }
                return false;
            }
        });
    }

    private void performSearch(){
        String query = etSearch.getText().toString().trim();
        if (query.isEmpty()){
            Toast.makeText(this,"请输入城市名",Toast.LENGTH_SHORT).show();
            return;
        }

        if (cityWeatherList == null || cityWeatherList.isEmpty()) {
            Toast.makeText(this, "天气数据尚未加载完成", Toast.LENGTH_SHORT).show();
            return;
        }

        // 搜索匹配的城市
        for (int i = 0; i < cityWeatherList.size(); i++) {
            WeatherResponse.CityWeather cityWeather = cityWeatherList.get(i);
            if (cityWeather.getCityInfo().getCity().contains(query)) {
                citySpinner.setSelection(i);
                updateWeatherUI(cityWeather);
                return;
            }
        }

        Toast.makeText(this, "未找到匹配的城市", Toast.LENGTH_SHORT).show();
    }

    private void setupShareButton(){
        btnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cityWeatherList != null && !cityWeatherList.isEmpty()) {
                    int position = citySpinner.getSelectedItemPosition();
                    if (position >= 0 && position < cityWeatherList.size()) {
                        WeatherResponse.CityWeather currentCity = cityWeatherList.get(position);
                        shareWeather(currentCity);
                    }
                } else {
                    Toast.makeText(MainActivity.this, "请等待天气数据加载完成", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void setupTimeUpdater() {
        timeHandler = new Handler();
        timeRunnable = new Runnable() {
            @Override
            public void run() {
                updateCurrentTime();
                timeHandler.postDelayed(this, 1000); // 每秒更新一次
            }
        };
        timeHandler.post(timeRunnable);
    }

    private void updateCurrentTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String currentDateTime = dateFormat.format(new Date());
        tvTime.setText("当前时间：" + currentDateTime);
    }

    private  void loadWeatherData(){ new  WeatherTask().execute(url); }

    private void shareWeather(WeatherResponse.CityWeather cityWeather) {
        try {
            WeatherResponse.CityInfo cityInfo = cityWeather.getCityInfo();
            WeatherResponse.WeatherData data = cityWeather.getData();
            WeatherResponse.Forecast todayForecast = data.getForecast().get(0);

            String shareText = String.format(Locale.getDefault(),
                    "【%s天气】\n" +
                            "当前温度: %s\n" +
                            "天气状况: %s\n" +
                            "温度范围: %s\n" +
                            "湿度: %s\n" +
                            "PM2.5: %.1f\n" +
                            "更新时间: %s\n" +
                            "来自天气APP的分享",
                    cityInfo.getCity(),
                    data.getWendu(),
                    todayForecast.getType(),
                    todayForecast.getLow() + " ~ " + todayForecast.getHigh(),
                    data.getShidu(),
                    data.getPm25(),
                    getCurrentTime()
            );

            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, shareText);
            startActivity(Intent.createChooser(shareIntent, "分享天气到"));
        } catch (Exception e) {
            Toast.makeText(this, "分享失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private String getCurrentTime(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return dateFormat.format(new Date());
    }

    private class WeatherTask extends AsyncTask<String,Void,WeatherResult>{
        @Override
        protected WeatherResult doInBackground(String... urls){
            try {
                String jsonResponse = NetworkUtils.fetchWeatherData(urls[0]);
                WeatherResponse response = WeatherParser.parse(jsonResponse);
                return new WeatherResult(response,null);
            }catch (Exception e){
                return new WeatherResult(null,e.getMessage());
            }
        }
        @Override
        protected void onPostExecute(WeatherResult result) {
            if(result.error!=null){
                showError(result.error);
            }else if(result.response!=null && result.response.getStatus()==200) {
                cityWeatherList = result.response.getCities();

                if (cityWeatherList != null && !cityWeatherList.isEmpty()) {
                    List<String> cityNames = new ArrayList<>();
                    for (WeatherResponse.CityWeather cityWeather : cityWeatherList) {
                        cityNames.add(cityWeather.getCityInfo().getCity());
                    }

                    cityAdapter = new ArrayAdapter<>(
                            MainActivity.this,
                            android.R.layout.simple_spinner_item,
                            cityNames
                    );
                    cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    citySpinner.setAdapter(cityAdapter);

                    // 设置城市选择监听器
                    citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            updateWeatherUI(cityWeatherList.get(position));
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });
                            // 默认显示第一个城市
                    updateWeatherUI(cityWeatherList.get(0));
                }
            }else {
                    showError("未知错误");
                }
            }
        }

    private void showError(String errorMessage){
        Toast.makeText(this,"加载失败："+errorMessage,Toast.LENGTH_LONG).show();
        tvCity.setText("城市：数据加载失败（"+errorMessage+"）");
    }
    private void updateWeatherUI(WeatherResponse.CityWeather cityWeather) {
        WeatherResponse.CityInfo cityInfo = cityWeather.getCityInfo();
        WeatherResponse.WeatherData data = cityWeather.getData();

        tvTemperature.setText(data.getWendu() + "℃");
        tvCity.setText("城市：" + cityInfo.getCity());
        tvHumidity.setText("湿度：" + data.getShidu());
        tvPm25.setText("PM2.5：" + data.getPm25());

        setWeatherIcon(ivWeatherIcon, data.getForecast().get(0).getType());
        setBackgroundImage(data.getForecast().get(0).getType());
        rvForecast.setAdapter(new ForecastAdapter(data.getForecast()));
    }

    private void setWeatherIcon(ImageView imageView,String weatherType){
        int iconResource;
        if (weatherType.contains("晴")) {
            iconResource = R.drawable.sunny;
        } else if (weatherType.contains("云") || weatherType.contains("阴")) {
            iconResource = R.drawable.cloudy;
        } else if (weatherType.contains("雨")) {
            iconResource = R.drawable.rainy;
        } else if (weatherType.contains("雪")) {
            iconResource = R.drawable.snowy;
        } else {
            iconResource = R.drawable.default_weather;
        }
        imageView.setImageResource(iconResource);
    }

    private void setBackgroundImage(String weatherType){
        final int bgResource;
        if (weatherType.contains("晴")){
            bgResource = R.drawable.bg_sunny;
        }else if (weatherType.contains("云") || weatherType.contains("阴")) {
            bgResource = R.drawable.bg_cloudy;
        } else if (weatherType.contains("雨")) {
            bgResource = R.drawable.bg_rainy;
        } else if (weatherType.contains("雪")) {
            bgResource = R.drawable.bg_snowy;
        } else {
            bgResource = R.drawable.bg_default;
        }

        Animation fadeOut = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
        final Animation fadeIn = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);

        fadeOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {}

            @Override
            public void onAnimationEnd(Animation animation) {
                ivBackground.setImageResource(bgResource);
                ivBackground.startAnimation(fadeIn);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {}
        });

        ivBackground.startAnimation(fadeOut);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timeHandler.removeCallbacks(timeRunnable);
    }

    private static class WeatherResult{
        WeatherResponse response;
        String error;

        WeatherResult(WeatherResponse response,String error){
            this.response = response;
            this.error = error;
        }
    }
}
